//: \$dmd2 \console -L+pcre+fcgi+ws2_32 \+..\jade \+..\dmdscript  \+..\fcgi -O -release -inline \clean 

module jade.examples.fcgi;

import jade.Jade, fcgi4d.all ;
import std.process;

version(Windows){}else{
	pragma(lib, "jade");
	pragma(lib, "pcre");
	pragma(lib, "fcgi");
}


private class User {
	int id		= 1983 ;
	int thread_id	= 0 ;
	bool login	= true ;
	bool admin	= false ;
	string name		= "Chang Long";
	
}


User 		user ;
DTpl_Object	user_list ;
string[string]	items ;

static this(){
	Tpl_Factory.Init("./tpl.js") ;
	user_list	= Tpl_Factory.Create("UserList", "./example.jade" );
	
	items["1"] = "One";
	items["2"] = "Two";
	items["3"] = "Three";
	user_list.assign(items, "items");
	
	user = new User ;
	user_list.assign(user, "user");
	
	user_list.assign(environment.toAA, "env");

}


public int run (FCGI_Request req){
	auto stdout = req.stdout ;
	
	ubyte[1024 * 15] _tmp_bu;
	scope _bu = new vBuffer(_tmp_bu);
	
	_bu( "thread_id =")( req.thread_id)  (" <br /> \n") ;
	foreach(int i, _field; req.header.tupleof){
		_bu ( req.header.key!i() )(" => ")( _field ) (" <br /> \n");
	}
	
	user.thread_id	= req.thread_id ;
	
	user_list.assign(_bu.toString, "header");
	user_list.assign("Jade fcgi test page", "page_title");
	

	StopWatch sw;
	sw.start;
	string _html	= user_list.render ;
	sw.stop;
	
	stdout("Status: 200 OK\r\n");
	stdout("Content-Type: text/html\r\n");
	stdout("Render-Time: ")(sw.peek.msecs)( "ms \r\n");
	stdout("Content-Length: ")( _html.length)( "\r\n");
	stdout("\r\n");
	stdout(_html);
	

	user.id ++ ;
	user.login	= !user.login;
	if( user.id % 3 is 0 )
		user.admin	= !user.admin;
	
	return 0;
}

void main() {
	auto conn	= new shared(FCGI_Connection)(null, "1983" );
	FCGI_Application.loop!run(conn, true, 4) ;
}
